<template>
	<view class="nav">
		<image src="@/static/images/logo.png"></image>
		<u-button @click="login()">点击登录</u-button>
		<button @click="login2()" class="myBtn" >一键获取手机号</button>
		<navigator url="/pages/login/bindMobile" open-type="navigate"> 获取手机号</navigator>
	</view>
</template>

<script>
import {loginByWechatAPI,registerAPI} from '@/utils/api/login.js'
	export default {
		data() {
			return {
			}
		},
		methods: {
			login2(){
				uni.login({
					provider:'weixin',
					onlyAuthorize:true,
					success(lres) {
						console.log(lres)
					}
				})
			},
			login(){
				const that = this
					uni.getUserProfile({
						desc:'获取个人信息，用于登录',
						success(ures) {
							//这个是成功的回调
							uni.login({
								provider:'weixin',
								onlyAuthorize:true,
								success(lres) {
									const params = {code:lres.code}
								 	that.loginByWechat(params)
								},
							})
						}
					})
			},
			//调用一键登录微信的api
			loginByWechat(params){
				const that = this
				loginByWechatAPI(params).then(res=>{
					console.log(res)
					//用户未注册
					if(String(res.code) === '60003'){
						//注册用户
						const data = {
							unionId:res.data.unionId?
								res.data.unionId:res.data.openid,
							openId:res.data.openid,
							sessionKey:res.data.sessionKey,
							signature:ures.signature,
							rawData:ures.rawData,
							signature:ures.signature,
							encryptedData:ures.encryptedData,
							iv:ures.iv
						}
						console.log(data)
						registerAPI(data).then(res=>{
							console.log(res)
							//拿到用户token
							uni.setStorage({
								key:'banluUserToken',
								data:res.token
							})
						})
					}else if(res.code === "200"){
						//登录成功(用户之前登录过)
						that.isMobile(res.data)
					}
				})
			},
			//查询是否绑定过手机号
			isMobile(data){
				if(!data.member.mobile){
					//没有绑定过手机号
					uni.showModal({
						title:'提示信息',
						confirmText:'去完善',
						content:'根据国家规定，需要绑定手机号',
						success(res) {
							if(res.confirm){
								uni.navigateTo({
									url:'/pages/login/bindMobile'
								})
							}
						}
					})
				}
				//存储token
				uni.setStorage({
					key:'banlUserToken',
					data:data
				})
			}
		}
	}
</script>

<style>
.nav{
	width: 100%;
}
.myBtn{
	border: 1px solid saddlebrown;
	border-radius: 10rpx;
	width: 240rpx;
}
</style>
